package com.hisoka.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.hisoka.domain.MailAuth;
import com.hisoka.domain.MailInfo;
import com.hisoka.common.MailSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.MessagingException;

/**
 * @Auther hinsteny
 * @Date 2017-03-26
 * @copyright: 2017 All rights reserved.
 */
public abstract class EmailJobProcess implements SimpleJob {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void execute(ShardingContext context) {
        // TODO 业务逻辑
        logger.info("MySimpleJob jobName :{}, taskId: {}, param: {}", context.getJobName(), context.getTaskId(), context.getJobParameter());
        // 首先获取要发送的邮件信息
        MailAuth auth = getMailAuth(context);
        MailInfo mail = getMailInfo(context);
        try {
            if (null == auth)
                throw new Exception("Get send email account auth failed!");
            if (mail != null){
                MailSender.send(auth, mail);
                handleSuccess(mail);
            }
        } catch (MessagingException e) {
            handleFail(mail);
            logger.error("Run config failed for " + mail.getReceiver() + ", " + mail.getSubject(), e);
        } catch (Exception e){
            logger.error("Run config failed for ", e);
        }
    }

    /**
     * 获取到要发送邮件的发送方帐号信息
     * @return
     */
    public abstract MailAuth getMailAuth(ShardingContext context);

    /**
     * 获取到要发送的邮件内容及接收方帐号信息
     * @return
     */
    public abstract MailInfo getMailInfo(ShardingContext context);

    /**
     * 处理已经发送成功啦的邮件任务
     * @return
     */
    public abstract boolean handleSuccess(MailInfo mailInfo);

    /**
     * 处理发送失败了的邮件任务
     * @return
     */
    public abstract boolean handleFail(MailInfo mailInfo);
}
